import random
import re

from django_redis import get_redis_connection

from rest_framework.response import Response
from rest_framework.views import APIView

from six_it.models import User


class VerificationView(APIView):
    def get(self, request, mobile):
        """
        获取短信验证码
        """
        if not re.match(r'1[3-9]\d{9}', mobile):
            raise ValueError('手机号格式错误')
        redis_conn = get_redis_connection('verify_code')
        if redis_conn.get('send_flag_%s' % mobile):
            raise ValueError('发送频繁，稍后再试')

        if User.objects.filter(mobile=mobile):
            raise ValueError('手机号存在')

        code = '%06d' % random.randint(0, 999999)

        # 管道创建
        p1 = redis_conn.pipeline()
        # redis保存电话与验证码，保存倒计时时间
        p1.setex('sms_%s' % mobile, 300, code)
        p1.setex('send_flag_%s' % mobile, 60, 1)

        # 管道执行
        p1.execute()
        return Response({
            'success': True,
            'sms_code': code,
            'message': 'OK'
        })
